﻿using UnityEngine;
using System.Collections.Generic;
using System.Text.RegularExpressions;

public class LTLocalization
{

    public const string LANGUAGE_ENGLISH = "EN";
    public const string LANGUAGE_CHINESE = "CN";
    public const string LANGUAGE_JAPANESE = "JP";
    public const string LANGUAGE_FRENCH = "FR";
    public const string LANGUAGE_GERMAN = "GE";
    public const string LANGUAGE_ITALY = "IT";
    public const string LANGUAGE_KOREA = "KR";
    public const string LANGUAGE_RUSSIA = "RU";
    public const string LANGUAGE_SPANISH = "SP";

    private const string KEY_CODE = "KEY";
    private const string FILE_PATH = "LTLocalization/localization";

    private SystemLanguage language = SystemLanguage.Chinese;
    private Dictionary<string, string> textData = new Dictionary<string, string>();
    public List<LTLocalizationData> languageList = new List<LTLocalizationData>();

    private static LTLocalization mInstance;

    private LTLocalization()
    {
    }

    private static string GetLanguageAB(SystemLanguage language)
    {
        switch (language)
        {
            case SystemLanguage.Afrikaans:
            case SystemLanguage.Arabic:
            case SystemLanguage.Basque:
            case SystemLanguage.Belarusian:
            case SystemLanguage.Bulgarian:
            case SystemLanguage.Catalan:
                return LANGUAGE_ENGLISH;
            case SystemLanguage.Chinese:
            case SystemLanguage.ChineseTraditional:
            case SystemLanguage.ChineseSimplified:
                return LANGUAGE_CHINESE;
            case SystemLanguage.Czech:
            case SystemLanguage.Danish:
            case SystemLanguage.Dutch:
            case SystemLanguage.English:
            case SystemLanguage.Estonian:
            case SystemLanguage.Faroese:
            case SystemLanguage.Finnish:
                return LANGUAGE_ENGLISH;
            case SystemLanguage.French:
                return LANGUAGE_FRENCH;
            case SystemLanguage.German:
                return LANGUAGE_GERMAN;
            case SystemLanguage.Greek:
            case SystemLanguage.Hebrew:
            case SystemLanguage.Icelandic:
            case SystemLanguage.Indonesian:
                return LANGUAGE_ENGLISH;
            case SystemLanguage.Italian:
                return LANGUAGE_ITALY;
            case SystemLanguage.Japanese:
                return LANGUAGE_JAPANESE;
            case SystemLanguage.Korean:
                return LANGUAGE_KOREA;
            case SystemLanguage.Latvian:
            case SystemLanguage.Lithuanian:
            case SystemLanguage.Norwegian:
            case SystemLanguage.Polish:
            case SystemLanguage.Portuguese:
            case SystemLanguage.Romanian:
                return LANGUAGE_ENGLISH;
            case SystemLanguage.Russian:
                return LANGUAGE_RUSSIA;
            case SystemLanguage.SerboCroatian:
            case SystemLanguage.Slovak:
            case SystemLanguage.Slovenian:
                return LANGUAGE_ENGLISH;
            case SystemLanguage.Spanish:
                return LANGUAGE_SPANISH;
            case SystemLanguage.Swedish:
            case SystemLanguage.Thai:
            case SystemLanguage.Turkish:
            case SystemLanguage.Ukrainian:
            case SystemLanguage.Vietnamese:
            case SystemLanguage.Unknown:
                return LANGUAGE_ENGLISH;
        }
        return LANGUAGE_CHINESE;
    }

    private static string GetWinReadPath(string fileName)
    {
        //return Application.dataPath + "/../" + fileName + ".csv";
        return Application.dataPath + "/" + fileName + ".csv";
    }

    private static string GetWinSavePath(string fileName)
    {
        return Application.dataPath + "/Resources/LTLocalization/" + fileName + ".txt";
    }

    private void ReadData()
    {
#if UNITY_EDITOR
        //如果已经有数据，在重新读取前要先保存
        if(languageList.Count > 0) {
            SaveDataToCSV();
            //重置语言列表
            languageList = new List<LTLocalizationData>();
        }
        // 在Windows平台下读取语言配置文件
        string CSVFilePath = GetWinReadPath(FILE_PATH);
        LTCSVLoader loader = new LTCSVLoader();
        loader.ReadFile(CSVFilePath);
        // 将配置文件序列化为多个语言类
        int csvRow = loader.GetRow();
        int csvCol = loader.GetCol();
        Debug.Log("row:" + csvRow + "col:" + csvCol);
        for (int tempCol = 1; tempCol < csvCol; ++tempCol)
        {
            LTLocalizationData languageData = new LTLocalizationData();
            // 获取第一行数据(语言类型)
            languageData.LanguageType = loader.GetValueAt(tempCol, 0);
            // 遍历生成变量
            languageData.LanguageData = new Dictionary<string, string>();
            for (int tempRow = 1; tempRow < csvRow; ++tempRow)
            {
                languageData.LanguageData.Add(loader.GetValueAt(0, tempRow), loader.GetValueAt(tempCol, tempRow));
            }
            // 将语言对象序列化存档
            SaveHelper.SaveData(GetWinSavePath(languageData.LanguageType), languageData);
            languageList.Add(languageData);

            if (GetLanguageAB(language).Equals(languageData.LanguageType))
            {
                textData = languageData.LanguageData;
            }
        }
#else
    // 读取对应的语言对象
    TextAsset tempAsset = (TextAsset)Resources.Load("LTLocalization/" + GetLanguageAB(language), typeof(TextAsset));
    if (null == tempAsset)
    {
        tempAsset = (TextAsset)Resources.Load("LTLocalization/" + "EN", typeof(TextAsset));
    }
    if (null == tempAsset)
    {
        Debug.LogError("未检测到语言配置文件");
    }
    else
    {
        string saveData = tempAsset.text;
        LTLocalizationData currentLanguageData = (LTLocalizationData)SaveHelper.ReadData<LTLocalizationData>(saveData, false);
        textData = currentLanguageData.LanguageData;
    }
#endif
    }

    private void SetLanguage(SystemLanguage language)
    {
        this.language = language;
    }

    public static void Init()
    {
        mInstance = new LTLocalization();
        mInstance.SetLanguage(Application.systemLanguage);
        mInstance.ReadData();
    }

    public static void ManualSetLanguage(SystemLanguage setLanguage)
    {
        if (null == mInstance)
        {
            mInstance = new LTLocalization();
        }
        mInstance.SetLanguage(setLanguage);
        mInstance.ReadData();
    }
    /// <summary>
    /// 是否包含指定key
    /// </summary>
    /// <param name="key"></param>
    /// <returns></returns>
    public static bool IsContain(string key)
    {
        if (null == mInstance)
        {
            Init();
        }
        return mInstance.textData.ContainsKey(key);
    }
    /// <summary>
    /// 获取对应key的文本
    /// "这只{age}是一{test}个测试{name}"
    /// data对应上面字符串里面键值的字典会自动进行替换
    /// </summary>
    /// <param name="key"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string GetText(string key,Dictionary<string,object> data = default(Dictionary<string,object>))
    {
        if (null == mInstance)
        {
            Init();
        }

        if (mInstance.textData.ContainsKey(key))
        {
            var str = mInstance.textData[key];
            if (data != null && data.Count > 0)
            {
                var match = Regex.Matches(str, @"\{(.*?)\}");
                foreach (Match item in match)
                {
                    var _key = Regex.Replace(item.Value, @"\{*\}*", "");
                    str = str.Replace(item.Value, data.GetValue(_key,item.Value).ToString());
                }
            }
            return str;
        }
        return "[NoDefine]" + key;
    }
    /// <summary>
    /// 获取对应key的文本
    /// "这只?是一?个测试?"
    /// data对应上面字符串里面?，要按顺序12-15(以-隔开)
    /// </summary>
    /// <param name="key"></param>
    /// <param name="data"></param>
    /// <returns></returns>
    public static string GetText2(string key, string data = "")
    {
        if (null == mInstance)
        {
            Init();
        }

        if (mInstance.textData.ContainsKey(key))
        {
            var str = mInstance.textData[key];
            var dataArr = data.Split('-');
            if (dataArr.Length > 0 && data != "")
            {
                var match = Regex.Matches(str, @"\?");
                var index = 0;
                foreach (Match item in match)
                {
                    //只替换匹配的第一项
                    var regex = new Regex(@"\?");
                    if (index < dataArr.Length) str = regex.Replace(str, dataArr[index++],1);
                }
                str = str.Replace("-?%","");
                str = str.Replace("-?","");
            }
            return str;
        }
        return "[NoDefine]" + key;
    }
    /// <summary>
    /// 添加或修改对应key的文本内容
    /// </summary>
    /// <param name="key"></param>
    /// <param name="text"></param>
    public static void AddText(string key,string text)
    {
        if (null == mInstance)
        {
            Init();
        }
        //如果是新加的，要在其它语言上也加上
        for (int i = 0;i < mInstance.languageList.Count; i++)
        {
            var _textData = mInstance.languageList[i];
            if(!_textData.LanguageData.ContainsKey(key)) _textData.LanguageData.AddOrReplace(key, text);
        }
        //修改或添加到本次使用语言内
        mInstance.textData.AddOrReplace(key,text);
    }
    /// <summary>
    /// key1的值为key2
    /// </summary>
    /// <param name="key1"></param>
    /// <param name="key2"></param>
    public static void ReplaceKey(string key1,string key2)
    {
        if (null == mInstance)
        {
            Init();
        }
        //如果是新加的，要在其它语言上也加上
        for (int i = 0; i < mInstance.languageList.Count; i++)
        {
            var _textData = mInstance.languageList[i];
            _textData.LanguageData.AddOrReplace(key1, _textData.LanguageData.GetValue(key2, "[NoDefine]" + key2));
        }
    }
    /// <summary>
    /// 删除文本
    /// </summary>
    /// <param name="key"></param>
    public static void DelKey(string key)
    {
        //从所有语言中删除
        for (int i = 0; i < mInstance.languageList.Count; i++)
        {
            var _textData = mInstance.languageList[i];
            _textData.LanguageData.Remove(key);
        }
    }
    /// <summary>
    /// 重新保存语言文件
    /// </summary>
    public static void SaveDataToCSV(){
        if(null == mInstance) return;
        string CSVFilePath = GetWinReadPath(FILE_PATH);
        SaveHelper.SaveCSV(mInstance.languageList, CSVFilePath);
    }
    /// <summary>
    /// 获取所有语言列表
    /// </summary>
    /// <returns></returns>
    public static List<LTLocalizationData> GetLanguageList()
    {
        if (null == mInstance)
        {
            Init();
        }
        return mInstance.languageList;
    }
}
